let babel = require('babel-core');//babel核心库
let types = require('babel-types');
let fs = require('fs');
let path = require('path');

console.log(process.argv);
// 第一个参数：源文件路径。../tmp/code.js  第二个参数：编译成功的文件名。
let basicSrcPath = process.argv[2];
let buildAstPath = process.argv[3];

function walk(currentDirPath, callback) {
  fs.readdir(currentDirPath, function (err, files) {
    if (err) {
      throw new Error(err);
    }
    files.forEach(function (name) {
      var filePath = path.join(currentDirPath, name);
      var stat = fs.statSync(filePath);
      if (stat.isFile()) {
        callback(filePath, stat);
      } else if (stat.isDirectory()) {
        walk(filePath, callback);
      }
    });
  });
}

function buildAst(codePath){
  let astPath = codePath
      .replaceAll("\\", "/")
      .replaceAll(".js", ".json")
      .replaceAll(basicSrcPath, buildAstPath);
  console.log(astPath);
  let code = fs.readFileSync(codePath, 'utf8');
// let visitor = {
//     ArrowFunctionExpression(path) {//定义需要转换的节点
//         let params = path.node.params
//         let blockStatement = path.node.body
//         let func = types.functionExpression(null, params, blockStatement, false, false)
//         path.replaceWith(func) //
//     }
// }

// let arrayPlugin = { visitor }
  let result = babel.transform(code, {
    plugins: [
      // arrayPlugin
    ]
  });

  let ast = result.ast;
  delete ast.tokens;
  ast.srcPath = codePath.replaceAll("\\", "/");
  let json = JSON.stringify(ast, null, '  ');

  let outDir = astPath.replaceAll(/[/\\]\w+.json/g, "")
  mkdirsSync(outDir);
  fs.writeFile(astPath, json , function (err) {
    if (err) {
      console.error(err);
    }
  })

}

try {
  // fs.rmdirSync(buildAstPath);
  walk(basicSrcPath, function(filePath) {
    buildAst(filePath)
  });

}catch (e) {
  console.log(e);
  throw e;
}

function mkdirsSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
}